<template>
  <v-layout v-if="currentVideo" full-height>
    <v-navigation-drawer app permanent v-model="drawer" location="right" :width="350" style="background-color: #252632;">
      <v-card elevation="0" color="background" class="pa-4" id="videoPlayList">
        <VideoCard :overlay="currentIndex == index" class="mb-4" :video-info="videoItem"
          v-for="(videoItem, index) in similarList" :key="index" @click="currentIndex = index" />
      </v-card>
    </v-navigation-drawer>
    <v-main>
      <v-card rounded="0" width="100%" height="100%">
        <video ref="video" class="video-js vjs-default-skin" controls :poster="currentVideo.playCover">
          <source :src="currentVideo.playUrl" :type="currentVideo.videoType || 'video/mp4'" />
        </video>
        <div style="position: absolute;left: 15px;top: 15px;z-index: 99999;">
          <v-btn size="40" color="bg" icon v-if="!hideClose" @click="closeVideo">
            <v-icon :size="20">mdi-close</v-icon>
          </v-btn>
        </div>
        <div class="video-actions">
          <!-- 用户头像 -->
          <div class="action-item">
            <div class="action-icon-wrap avatar-wrap" @click="likeUser()">
              <v-avatar :image="currentVideo.user.avatar?apiFileGet(currentVideo.user.avatar): '/logo.png'" class="action-avatar"></v-avatar>
              <div class="plus-icon">
                <v-icon size="18" color="white">mdi-plus</v-icon>
              </div>
            </div>
          </div>
          
          <!-- 点赞按钮 -->
          <div class="action-item">
            <div class="action-icon-wrap" @click="starVideo()">
              <div class="action-icon" :class="{'liked': isLikeVideo}">
                <v-icon size="22" :color="isLikeVideo ? 'white' : 'white'">mdi-heart</v-icon>
              </div>
            </div>
            <span class="action-count">{{ currentVideo.startCount }}</span>
          </div>
          
          <!-- 收藏按钮 -->
          <div class="action-item">
            <FavoriteCom :video-id="currentVideo.id" :callback="favoriteCallBack">
              <template #default="{ props }">
                <div class="action-icon-wrap" v-bind="props">
                  <div class="action-icon favorite-icon">
                    <v-icon size="22" color="white">mdi-bookmark</v-icon>
                  </div>
                </div>
                <span class="action-count">{{ currentVideo.favoritesCount }}</span>
              </template>
            </FavoriteCom>
          </div>
          
          <!-- 分享按钮 -->
          <div class="action-item">
            <div class="action-icon-wrap" @click="copyUrl()">
              <div class="action-icon share-icon">
                <v-icon size="22" color="white">mdi-share-variant</v-icon>
              </div>
            </div>
            <span class="action-count">分享</span>
          </div>
          
          <!-- 更多按钮 -->
          <div class="action-item">
            <div class="action-icon-wrap" @click="openRgihtD()">
              <div class="action-icon more-icon">
                <v-icon size="22" color="white">mdi-menu</v-icon>
              </div>
            </div>
            <span class="action-count">更多</span>
          </div>
        </div>
        <v-snackbar v-model="snackbar.show" :color="snackbar.color">
          {{ snackbar.text }}

          <template v-slot:actions>
            <v-btn color="blue" variant="text" @click="snackbar.show = false">
              了解
            </v-btn>
          </template>
        </v-snackbar>
      </v-card>
    </v-main>
  </v-layout>
</template>
<script setup>
import { computed, getCurrentInstance, nextTick, onMounted, onUnmounted, ref, watch } from 'vue';
import { apiFileGet } from '../../apis/file';
import { apiFollows } from '../../apis/user/like';
import { apiAddHistory, apiGetVideoBySimilar, apiInitFollowFeed, apiSetUserVideoModel, apiShareVideo, apiStarVideo } from '../../apis/video';
import FavoriteCom from '../../components/favorite/index.vue';
import VideoCard from '../../components/video/card.vue';
import strUtils from '../../utils/strUtil';
const props = defineProps({
  videoInfo: {
    type: Object,
    default: null
  },
  videoList: {
    type: Array,
    default: []
  },
  hideClose: {
    type: Boolean,
    default: false
  },
  nextVideo: {
    type: Function,
    default: () => {

    }
  },
  closeVideo: {
    type: Function,
    default: () => { }
  }
})
const snackbar = ref({
  show: false,
  text: ""
})

const shareBtn = ()=>{
  apiShareVideo(currentVideo.value.id)
}

const handleMouseWheel = (event) =>{
  console.log(event.deltaY)
  if(event.deltaY >0) {
    if (currentIndex.value >= similarList.value.length - 1) {
        return;
      }
      currentIndex.value++;
  }else {
    if (currentIndex.value < 1) {
        return;
      }
      currentIndex.value--
  }
}
const drawer = ref(true)
const instance = getCurrentInstance().proxy
const video = ref()
const videoPlayer = ref()
const similarList = ref([
  props.videoInfo
])

const currentIndex = ref(0)
const currentVideo = computed(() => {

  let temp = currentIndex.value >= 0 ? similarList.value[currentIndex.value] : props.videoInfo
  temp.playUrl = apiFileGet(temp.url)
  temp.playCover = apiFileGet(temp.cover)
  console.log(temp, "aa")
  return temp
})
const openRgihtD = () => {
  drawer.value = !drawer.value
}
const favoriteCallBack = (e) => {
  if (e == "已收藏") {
    currentVideo.value.favoritesCount++
  } else {
    currentVideo.value.favoritesCount--
  }
  snackbar.value = {
    show: true,
    text: e
  }
}
const isAddHistory = ref(true)
const isLikeVideo = ref(false)
const windowKeyEvent = (event) => {
  switch (event.which) {
    case 38:
      if (currentIndex.value < 1) {
        return;
      }
      currentIndex.value--
      break
    case 40:
      if (currentIndex.value >= similarList.value.length - 1) {
        return;
      }
      currentIndex.value++;
      break
    case 27:
      props.closeVideo()
      break
    case 70:
      videoPlayer.value.requestFullscreen()
      break
  }
}
const copyUrl = () => {
  shareBtn()
  snackbar.value = {
    text: strUtils.copyContent(location.host + "/#/?play=" + currentVideo.value.id) ? "视频地址复制成功" : "视频地址复制失败",
    show: true
  }
}
onUnmounted(() => {
  document.removeEventListener('wheel', handleMouseWheel);
  window.removeEventListener("keydown", windowKeyEvent)
})

const firstInitVideo = () => {
  console.log(currentVideo)
  if (videoPlayer.value || !currentVideo.value) return;
  videoPlayer.value = instance.$video(video.value, {
    playbackRates: [0.5, 1, 1.5, 2],
    notSupportedMessage: "暂不支持该视频类型",
    fill: true,
    autoplay: true
  })
  videoPlayer.value.volume(localStorage.getItem("volume") || 1)
  document.addEventListener('wheel', handleMouseWheel);
  window.addEventListener("keydown", windowKeyEvent)
  videoPlayer.value.on("volumechange", () => {
    localStorage.setItem("volume", videoPlayer.value.volume())
  })
  videoPlayer.value.on("timeupdate", function () {
    // 播放三秒后添加历史记录
    if (this.currentTime() >= 3 && isAddHistory.value) {
      isAddHistory.value = false
      apiAddHistory(currentVideo.value.id)
    }
    let duration = this.duration()
    let score = this.currentTime() >= (duration / 5)
    if (score) {
      if (!isLikeVideo.value)
        apiSetUserVideoModel(currentVideo.value.id, currentVideo.value.labelNames, 1)
      isLikeVideo.value = true;
    } else isLikeVideo.value = false

  })
  nextTick(() => {
    video.value.style['background-image'] = `url(${currentVideo.playCover})`
    videoPlayer.value.play()
  })
  if (props.videoList.length == 0) {
    apiGetVideoBySimilar(props.videoInfo.labelNames, props.videoInfo.id).then(({ data }) => {
      similarList.value = similarList.value.concat(data.data)
    })
  }

}
const likeUser = () => {
  apiFollows(currentVideo.value.user.id).then(({ data }) => {
    if (data.message == '已关注') {
      apiInitFollowFeed()
    }
    snackbar.value = {
      text: data.message,
      show: true
    }
  })
}
onMounted(() => {
  video.value.style['background-size'] = " cover"
  video.value.style['background-position'] = "center"
  video.value.style['backdrop-filter'] = "blur(50px)"
  if (document.documentElement.clientWidth < 800)
    drawer.value = false
  firstInitVideo()
})

const starVideo = () => {

  apiStarVideo(currentVideo.value.id).then(({ data }) => {
    snackbar.value = {
      show: true,
      text: data.message
    }
    if (!data.state) {
      return;
    }
    if (data.message == "已点赞") {
      currentVideo.value.startCount++
    } else {
      currentVideo.value.startCount--
    }


  })
}
const playVideo = (n) => {
  if (n) {
    props.nextVideo(currentIndex.value)
    // videoPlayer.value.reset()
    setTimeout(() => {
      video.value.style['background-image'] = `url(${n.playCover})`

      firstInitVideo()
      isAddHistory.value = true
      videoPlayer.value.src([
        {
          src: n.playUrl,
          type: n.videoType,
          poster: n.playCover
        }
      ])
      videoPlayer.value.load()
      videoPlayer.value.play()
      apiSetUserVideoModel(n.id, n.labelNames, -0.5)
    }, 10)
  }
}
watch(() => props.videoList, () => {
  if (props.videoList && props.videoList.length > 0) {
    similarList.value = props.videoList
  }
}, {
  immediate: true,
  deep: true
})
watch(currentVideo, playVideo)


</script>   
<style scoped>
.video-js {
  width: 100%;
  height: 100%;
}

.video-actions {
  position: absolute;
  right: 16px;
  bottom: 100px;
  z-index: 99;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 14px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.action-icon-wrap {
  position: relative;
  margin-bottom: 2px;
  cursor: pointer;
}

.action-icon {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background-color: rgba(33, 33, 33, 0.85);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.25s ease;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
  will-change: transform, background-color;
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.15);
}

.action-icon:hover {
  transform: scale(1.05);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.3);
}

.action-count {
  font-size: 11px;
  font-weight: 600;
  color: #fff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
  margin-top: 1px;
}

/* 头像样式 */
.avatar-wrap {
  width: 40px;
  height: 40px;
}

.action-avatar {
  width: 100%;
  height: 100%;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
  border: 1.5px solid rgba(255, 255, 255, 0.9);
  transition: all 0.3s ease;
}

.avatar-wrap:hover .action-avatar {
  transform: scale(1.05);
  border-color: #82a9d1;
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.35);
}

.plus-icon {
  position: absolute;
  right: -2px;
  bottom: -2px;
  width: 16px;
  height: 16px;
  background: linear-gradient(135deg, #5c8cbe, #4a71a0);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transform: scale(0.8);
  transition: all 0.25s ease;
  box-shadow: 0 1px 3px rgba(0,0,0,0.3);
  border: 1px solid rgba(255, 255, 255, 0.9);
}

.avatar-wrap:hover .plus-icon {
  opacity: 1;
  transform: scale(1);
}

/* 点赞按钮样式 */
.liked {
  background: linear-gradient(45deg, #ff3a68, #ff6b8b);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 3px 8px rgba(255, 77, 126, 0.35);
}

.action-icon-wrap:hover .action-icon:not(.liked) {
  background-color: rgba(61, 61, 61, 0.9);
  border-color: rgba(255, 255, 255, 0.25);
}

/* 收藏按钮样式 */
.action-icon-wrap:hover .favorite-icon {
  background-color: rgba(61, 61, 61, 0.9);
  border-color: rgba(255, 255, 255, 0.25);
}

/* 分享按钮样式 */
.action-icon-wrap:hover .share-icon {
  background-color: rgba(61, 61, 61, 0.9);
  border-color: rgba(255, 255, 255, 0.25);
}

/* 更多按钮样式 */
.action-icon-wrap:hover .more-icon {
  background-color: rgba(61, 61, 61, 0.9);
  border-color: rgba(255, 255, 255, 0.25);
}

/* 针对手机适配 */
@media (max-width: 600px) {
  .video-actions {
    right: 12px;
    bottom: 80px;
    gap: 12px;
  }
  
  .action-icon {
    width: 36px;
    height: 36px;
  }
  
  .avatar-wrap {
    width: 38px;
    height: 38px;
  }
  
  .action-count {
    font-size: 10px;
  }
}
</style>